
<template>
<div class="input-number" :style="outerStyle">
  <input type="number" class="value-input" v-on:blur="handleChange(value)" v-model="value" />
  <button v-if="controls" class="input-number-controls minus control" v-on:click="handleChange(value - 1)">-</button>
  <button v-if="controls" class="input-number-controls plus control" v-on:click="handleChange(value + 1)">+</button>
</div>
</template>

<script>
export default {
  name: 'input-number',
  props: {
    min: {
      type: Number
    },
    max: {
      type: Number,
      required: false
    },
    outerStyle: {
      type: String
    },
    change: {
      type: Function
    },
    controls: {
      type: Boolean,
      default: true
    },
    amount: {
      type: Number,
      required: true,
      default: 0
    },
    customFun: {
      type: Function
    },
    items: {
      type: Array
    },
    itemIndex: {
      type: Number
    }
  },
  data() {
    return {
      value: this.amount
    }
  },
  watch: {
    value() {
      if (this.value == null || this.value == undefined) {
        this.value = 1
      }
    }
  },
  methods: {
    handleChange(value) {
      const toInt = parseInt(value)
      const {
        min,
        max
      } = this
      const originInputValue = this.value
      let self = this
      if (!Number.isFinite(toInt)) {
        this.value = min
      } else if (toInt <= 0) {
        this.value = 1
      } else {
        if (this.customFun) {
          let callback = function(flag) {
            if (!flag) {
              self.value = originInputValue
            } else {
              self.value = toInt
            }
          }
          this.customFun.call(this, toInt, callback)
        } else {
          this.value = toInt
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.input-number{
  height: 50px;
  width: 80px;
  position: relative;

  input{
    height: 100%;
    width: 60%;
    border: 1px solid #dde0e0;
    border-right: 0;
    text-align: center;
    outline: none;
    position: absolute;
    left: 0;
  }

  .input-number-controls{
    height: 50%;
    width: 40%;
    position: absolute;
    right: 0;
    border: 1px solid #dde0e0;
    background-color: #fff;
    outline: none;

    &.plus{
      bottom: 0;
    }
    &.minus{
      top: 0;
    }
  }
}
</style>
